package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.Utils.MD5Utils;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.User;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author 林道样
 * @date 2020-03-05 15:20
 */
@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private SetmealDao setmealDao;

    //根据手机号查询会员信息
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    //新增会员
    public void add(Member member) {
        //如果用户设置了密码，需要对密码进行md5加密
        String password = member.getPassword();
        if (password != null) {
            password = MD5Utils.md5(password);
            member.setPassword(password);
        }
        memberDao.add(member);
    }

    //根据月份查询会员数量
    public List<Integer> findMemberCountByMonths(List<String> months) {
        List<Integer> memberCounts = new ArrayList<>();
        if (months != null && months.size() > 0) {
            for (String month : months) {//2019.01
                String endTime = month + ".31";
                Integer memberCount = memberDao.findMemberCountBeforeDate(endTime);
                memberCounts.add(memberCount);
            }
        }
        return memberCounts;
    }

    /**
     * 分页展示会员信息
     *
     * @param queryPageBean
     * @return
     */
    public PageResult findPage(QueryPageBean queryPageBean) throws Exception {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Member> page = memberDao.selectByCondition(queryString);
        for (Member member : page) {
            Date birthday = member.getBirthday();
            if (birthday != null) {
                int age = this.getAgeByBir(birthday);
                member.setAge(age);
            }
            //根据user_id查询User
            Integer userId = member.getUser_id();
            if (userId != null) {
                User user = memberDao.selectUserByUserId(userId);
                member.setUser(user);
                String username = user.getUsername();
                member.setUsername(username);
            }
        }
        //page.getResult()

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 查询健康师信息
     *
     * @return
     */
    public List<User> findAll() {
        return memberDao.findAllUser();
    }

    //新增会员信息
    public void addMember(Member member) {
        memberDao.addMember(member);

    }

    /**
     * 编辑回写 Member
     *
     * @return
     */
    public Member findById(Integer id) {
        Member member = memberDao.findById(id);
        //获取member得userid
        Integer userId = member.getUser_id();

        //根据userid查找user 封装到member
        User user = memberDao.selectUserByUserId(userId);
        member.setUser(user);
        return member;
    }


    //编辑会员信息
    public void edit(Member member) {
        //根据username查找Userid
//        Integer user_id = memberDao.findUserIdByUsername(username);
        Integer user_id = member.getUser().getId();
        member.setUser_id(user_id);
        memberDao.edit(member);
    }


    //根据生日获取年龄
    public int getAgeByBir(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                age--;
            }
        }
        return age;

    }

    //根据id删除会员
    public void delete(Integer id) {
        Order order = orderDao.findById(id);
        if (order != null) {
            new RuntimeException();
        }
        memberDao.deleteById(id);

    }

    @Override
    public List<Map<String, Object>> getMemberReportData(Integer[] memberIds) {
        List<Map<String, Object>> list = new ArrayList();
        //遍历前台传过来的会员id数组
        for (Integer memberId : memberIds) {
            //创建map
            Map<String, Object> map = new HashMap();
            //根据会员id来查询会员信息,并把查询结果封装到member实体类中
            Member member = memberDao.findById(memberId);
            //将查询出来的会员对象存放进入map集合
            map.put("member", member);
            //创建list集合用来封装查询出来的套餐id和预约的地址信息
            List<Map<String, Object>> arrayList = new ArrayList<Map<String, Object>>();
            arrayList = orderDao.findSetmealIdAddressByMemberId(memberId);
            //创建list集合用来封装根据arrayList集合中的套餐id查询出来的套餐详情信息,以及ArrayList集合中的预约地址
//            List<Map<String,Object>> setmealAndAddressList=new ArrayList<Map<String,Object>>();
            List<Map<Setmeal, String>> setmealAndAddressList = new ArrayList<Map<Setmeal, String>>();
            //遍历ArrayList集合获取其中的每个元素map集合,包含套餐id,以及预约的地址
            for (Map<String, Object> setmealIdAndAddressMap : arrayList) {
                //获取套餐id
                Integer setmealId = (Integer) setmealIdAndAddressMap.get("setmealId");
                //根据获取的套餐id信息来查询套餐的详细信息
                Setmeal setmeal = setmealDao.findById(setmealId);
                //获取map集合中的地址信息
                String address = (String) setmealIdAndAddressMap.get("address");
                //创建一个map集合用来封装查询出来的套餐以及预约地址
                Map<Setmeal, String> setmealAndAddressMap = new HashMap<Setmeal, String>();
                //把获取到的套餐的信息和预约地址封装到setmealAndAddressMap集合中
                setmealAndAddressMap.put(setmeal, address);
                //将每一个套餐信息,以及预约地址封装到setmealAndAddressList集合中
                setmealAndAddressList.add(setmealAndAddressMap);
            }
            //将每个会员对应的套餐信息以及预约地址的信息封装到map集合中
            map.put("addressAndSetMeal", setmealAndAddressList);
            //将每一个会员的信息封装到list集合中
            list.add(map);
        }
        return list;
    }
}
